﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Fast.Extensions.DatabaseAccessor.EntityFrameworkCore
{
    /// <summary>
    /// Sql 操作仓储实现
    /// </summary>
    [SkipScan]
    public class SqlRepository : SqlRepository<DefaultDbContextLocator>, ISqlRepository
    {
        public SqlRepository(IServiceProvider serviceProvider) : base(serviceProvider)
        {

        }
    }
    /// <summary>
    /// Sql 操作仓储实现
    /// </summary>
    [SkipScan]
    public class SqlRepository<TDbContextLocator> : RootSqlRepository, ISqlRepository<TDbContextLocator>
        where TDbContextLocator : class, IDbContextLocator
    {
        public SqlRepository(IServiceProvider serviceProvider) : base(serviceProvider, typeof(TDbContextLocator))
        {

        }
    }
    /// <summary>
    /// Sql 操作仓储实现
    /// </summary>
    [SkipScan]
    public partial class RootSqlRepository : IRootSqlRepository
    {
        /// <summary>
        /// 服务提供器
        /// </summary>
        private readonly IServiceProvider _serviceProvider;

        public RootSqlRepository(IServiceProvider serviceProvider, Type dbContextLocator)
        {
            _serviceProvider = serviceProvider;

            var dbContextFunc = serviceProvider.GetRequiredService<Func<Type, DbContext>>();

            this.Context = dbContextFunc.Invoke(dbContextLocator);

            this.Database = Context.Database;
        }
        /// <summary>
        /// 数据库上下文
        /// </summary>
        public virtual DbContext Context { get; }
        /// <summary>
        /// 数据库操作对象
        /// </summary>
        public virtual DatabaseFacade Database { get; }

        /// <summary>
        /// 切换仓储
        /// </summary>
        /// <typeparam name="TChangeDbContextLocator">数据库上下文定位器</typeparam>
        /// <returns>仓储</returns>
        public virtual ISqlRepository<TChangeDbContextLocator> Change<TChangeDbContextLocator>()
             where TChangeDbContextLocator : class, IDbContextLocator
        {
            return _serviceProvider.GetService<ISqlRepository<TChangeDbContextLocator>>();
        }
    }

}
